package android.pot.com.smartcar.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.pot.com.smartcar.MainActivity;
import android.pot.com.smartcar.R;
import android.pot.com.smartcar.config.MyConfig;
import android.pot.com.smartcar.util.Utils;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;


/**
 * Created by zhaoshilu on 2017/7/17.
 */

public abstract class  BaseFragmentActivity extends FragmentActivity implements View.OnClickListener{
    protected TextView tvTitle;
    /**
     * 初始化控件
     **/
    protected abstract void initView();
    protected abstract void initData();
    /**
     * 添加监听事件
     **/
    protected abstract void addListener();


    @Override
    public void onClick(View v) {
        if (Utils.isFastDoubleClick(500)) {
            return;
        }
    }

    protected void showFragmentById(Fragment fragment, int fragmentLayoutId, String tag) {
        FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        if(!fragment.isAdded()){
            try {
                addFragmentById(fragment,fragmentLayoutId,tag);
            }catch (Exception e){

            }
        }

        //必须要更新fragment的状态，否则fragment某些属性会不同步
//        getSupportFragmentManager().executePendingTransactions();
        getSupportFragmentManager().beginTransaction();
        ft.show(fragment);
        /**
         * 大致意思是说我使用的 commit方法是在Activity的onSaveInstanceState()之后调用的，这样会出错，因为onSaveInstanceState
         方法是在该Activity即将被销毁前调用，来保存Activity数据的，如果在保存玩状态后再给它添加Fragment就会出错。解决办法就
         是把commit（）方法替换成 commitAllowingStateLoss()就行了
         */
        ft.commitAllowingStateLoss();

    }

    protected void hideFragment(Fragment fragment) {
        FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        ft.hide(fragment);
        ft.commitAllowingStateLoss();
    }

    protected void addFragmentById(Fragment fragment, int resLayoutId, String tag) {
        FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        String tranTag=makeFragmentTag(tag);
        ft.add(resLayoutId, fragment,tranTag);

        //not use addToBackStack
        ft.commitAllowingStateLoss();
    }

    protected void replaceFragmentById(Fragment fragment, int resLayoutId, String tag) {
        FragmentManager fm=getSupportFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        String tranTag=makeFragmentTag(tag);
        ft.replace(resLayoutId, fragment,tranTag);
        //use addToBackStack
        ft.addToBackStack(tranTag);
        ft.commit();
    }

    private String makeFragmentTag(String tag){
        return "fragmentTag:"+tag;
    }


    @Override
    protected void onResume() {
        super.onResume();
        File tempDir = new File(MyConfig.TEMP_IMG_PATH);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
    }


    protected void goHome(Context act) {
        startAct(act, MainActivity.class);
    }

    protected void startAct(Context context, Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        context.startActivity(intent);
    }

    protected void startAct(Context context, Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    protected void startActForResult(Context context, Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        ((Activity)context).startActivityForResult(intent,2000);
    }
    protected void startActForResult(Context context, Class<?> cls,Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        intent.putExtras(bundle);
        ((Activity)context).startActivityForResult(intent,2000);
    }
    protected void checkNetwork() {
        if (!Utils.isNetworkConnected(this)) {
            Utils.showToast(this, R.string.hint_please_check_network);
            return;
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public  boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = { 0, 0 };
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
}
